package com.sen.common.common.exception;

import com.sen.common.common.inter.RespCodeEnum;
import com.sen.common.common.response.MessageResult;
import com.sen.common.common.response.ResultMsgEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.sql.SQLException;

/**
 * 异常通用处理
 *
 * @author esJiang
 */
@Slf4j
@ResponseBody
public class DefaultExceptionAdvice {
    /**
     * IllegalArgumentException异常处理返回json
     * 返回状态码:400
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({IllegalArgumentException.class})
    public MessageResult badRequestException(IllegalArgumentException e) {
        return defHandler(ResultMsgEnum.PARSE_PARAM_ERROR, e);
    }


    /**
     * 返回状态码:405
     */
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public MessageResult handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        return defHandler(ResultMsgEnum.METHOD_NOT_ALLOWED, e);
    }

    /**
     * 返回状态码:415
     */
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler({HttpMediaTypeNotSupportedException.class})
    public MessageResult handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e) {
        return defHandler(ResultMsgEnum.UNSUPPORTED_MEDIA_TYPE, e);
    }

    /**
     * SQLException sql异常处理
     * 返回状态码:500
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler({SQLException.class})
    public MessageResult handleSQLException(SQLException e) {
        return defHandler(ResultMsgEnum.SQL_ERROR, e);
    }

    /**
     * BusinessException 业务异常处理
     * 返回状态码:500
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(BusinessException.class)
    public MessageResult handleException(BusinessException e) {
        return defHandler(e.getRespCodeEnum(), e);
    }

    /**
     * 所有异常统一处理
     * 返回状态码:500
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public MessageResult handleException(Exception e) {
        return defHandler(ResultMsgEnum.SYSTEM_ERROR, e);
    }

    private MessageResult defHandler(RespCodeEnum headMsgEnum, Exception e) {
        log.error(headMsgEnum.getMsg(), e);
        return MessageResult.reqFailed(headMsgEnum);
    }
}
